package com.micro.frog.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.micro.frog.common.base.PageRes;
import com.micro.frog.common.base.Result;
import com.micro.frog.common.exception.MaException;
import com.micro.frog.common.utils.BeanCopyUtil;
import com.micro.frog.rbac.dto.UserDetail;
import com.micro.frog.rbac.entity.UserDO;
import com.micro.frog.rbac.mapper.UserMapper;
import com.micro.frog.rbac.service.MenuService;
import com.micro.frog.rbac.service.UserService;
import com.micro.frog.rbac.util.CookieUtil;
import com.micro.frog.rbac.utils.CacheUtil;
import com.micro.frog.rbac.vo.UserVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * @author :  ljh
 * @date : 2018/4/10
 **/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {
    @Resource
    private MenuService menuService;

    /**
     * 检查是否已登录
     */
    @Override
    public boolean hasLogin(HttpServletRequest request) {
        String token = CookieUtil.getToken(request);
        return null != CacheUtil.get(token);
    }

    @Override
    public Result login(String loginName, String password, HttpServletRequest request, HttpServletResponse response) {
        UserDO user = new UserDO();
        user.setLoginName(loginName);
        List<UserDO> users = this.queryList(user);
        if (CollectionUtils.isEmpty(users)) {
            return Result.error("用户名不存在");
        }
        if (users.size() > 1) {
            return Result.error("登陆账号异常(存在多个)，请联系管理员");
        }
        user = users.get(0);
        if (new Integer(0).equals(user.getStatus())) {
            return Result.error("用户状态锁定，无法登陆");
        }
        if (!password.equals(user.getPassword())) {
            return Result.error("密码错误");
        }
        updateUserLoginTime(user);
        UserDetail userDetail = new UserDetail();
        userDetail.setId(user.getId());
        userDetail.setLoginName(user.getLoginName());
        userDetail.setUserName(user.getUserName());
        userDetail.setMenus(menuService.userMenus(user.getId(), user.getType()));
        String token = CookieUtil.createToken(response);
        CacheUtil.put(token, userDetail);
        return Result.success(userDetail);
    }

    private void updateUserLoginTime(UserDO user) {
        final Date current = new Date();
        UserDO updateUser = new UserDO();
        updateUser.setId(user.getId());
        if (user.getFirstLoginTime() == null) {
            updateUser.setFirstLoginTime(current);
        }
        updateUser.setLastLoginTime(current);
        this.updateById(updateUser);
    }

    @Override
    public List<UserDO> queryList(UserDO user) {
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted", "N");
        queryWrapper.setEntity(user);
        return this.list(queryWrapper);
    }


    @Override
    public Result<PageRes<UserDO>> queryPage(UserDO user, Integer pageNum, Integer pageSize) {
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(user);
        IPage<UserDO> iPage = this.page(new Page<>(pageNum, pageSize));
        return Result.success(PageRes.success(iPage.getCurrent(), iPage.getSize(), iPage.getTotal(), iPage.getRecords()));
    }

    @Override
    public Result add(UserVO req) {
        UserDO user = new UserDO();
        user.setLoginName(req.getLoginName());
        List<UserDO> users = this.queryList(user);
        if (CollectionUtils.isEmpty(users)) {
            return Result.error("用户名不存在");
        }
        BeanCopyUtil.copy(req, user);
        this.save(user);
        return Result.success("添加成功");
    }

    @Override
    public boolean delete(Long id) {
        UserDO user = new UserDO();
        user.setId(id);
        user.setIsDeleted("Y");
        return this.updateById(user);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Result update(UserVO req) {
        UserDO user = this.getById(req.getId());
        if (user == null) {
            return Result.error("用户不存在");
        }
        if (!user.getLoginName().equals(req.getLoginName())) {
            user = new UserDO();
            user.setLoginName(req.getLoginName());
            List<UserDO> list = this.queryList(user);
            if (!CollectionUtils.isEmpty(list)) {
                return Result.error("登陆名已存在");
            }
        }
        final Date current = new Date();
        BeanCopyUtil.copy(req, user);
        user.setUpdatedTime(current);
        boolean flag = this.updateById(user);
        if (flag) {
            throw new MaException("修改失败");
        }
        return Result.error("修改成功");
    }

    @Override
    public Result updateStatus(UserDO user) {
        boolean flag = this.updateById(user);
        if (flag) {
            throw new MaException("修改失败");
        }
        return Result.error("修改成功");
    }
}
